package Annuaire.impl;

import java.util.*;
import Annuaire.*;

public class ServiceImpl extends ServicePOA {

	private ArrayList<Adresse> knownAddresses;
	private Adresse elu;

	public ServiceImpl() {
		this.knownAddresses = new ArrayList<Adresse>();
	}

	@Override
	public Adresse senregistrer(Adresse monAdresse) {
		if (!knownAddresses.contains(monAdresse))
			knownAddresses.add(monAdresse);

		return elu;
	}

	@Override
	public void precedentEtSuivant(Adresse moi, AdresseHolder precedent,
			AdresseHolder suivant) throws UnknownSenderException {
		if (!knownAddresses.contains(moi))
			throw new UnknownSenderException();

		if (knownAddresses.size() > 1) {
			int foundPos = knownAddresses.indexOf(moi);

			if (foundPos > 0)
				precedent.value = knownAddresses.get(foundPos - 1);
			else
				precedent.value = knownAddresses.get(knownAddresses.size() - 1);

			if (foundPos < knownAddresses.size() - 1)
				suivant.value = knownAddresses.get(foundPos + 1);
			else
				suivant.value = knownAddresses.get(0);
		} else {
			precedent.value = moi;
			suivant.value = moi;
		}
	}

	@Override
	public void definirElu(Adresse moi) throws UnknownSenderException {
		if (!knownAddresses.contains(moi))
			throw new UnknownSenderException();
		
		elu = moi;
	}

	@Override
	public Adresse obtenirCentralisateur() {
		int ip = 0x0A000001; // 10.0.0.1
		int port = 1234;
		return new Adresse(ip, port);
	}

}
